<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>地址管理</title>
    <link rel="stylesheet" href="../js/element-ui/lib/theme-chalk/index.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f7fa;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .header {
            text-align: center;
            margin-bottom: 20px;
            padding-bottom: 20px;
            border-bottom: 1px solid #ebeef5;
        }
        .el-table {
            margin-top: 20px;
        }
        .el-tag {
            margin-right: 10px;
        }
        .operation-cell {
            display: flex;
            justify-content: space-around;
        }
        .add-button {
            margin-bottom: 10px;
            margin-right: 10px;
        }
        .loading-text {
            text-align: center;
            padding: 20px;
            color: #909399;
        }
        .pagination-container {
            margin-top: 20px;
            text-align: center;
        }
        /* 三级联动选择器样式 */
        .region-selector {
            display: flex;
            gap: 10px;
        }
        .region-selector .el-select {
            flex: 1;
        }
    </style>
</head>
<body>
<div id="app" class="container">
    <div class="header">
        <h2>收货地址管理</h2>
    </div>

    <div>
        <el-button type="primary" class="add-button" @click="handleAdd">新增地址</el-button>
        <el-button type="success" class="add-button" @click="setDefaultAddress"
                   :disabled="multipleSelection.length !== 1">设为默认地址</el-button>
    </div>

    <el-table
            :data="addressData"
            border
            style="width: 100%"
            v-loading="loading"
            @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="ID" width="80">
            <template #default="scope">
                {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
            </template>
        </el-table-column>
        <el-table-column prop="receiverName" label="收件人" width="120"></el-table-column>
        <el-table-column prop="phone" label="联系电话" width="150"></el-table-column>
        <el-table-column prop="detailAddress" label="详细地址">
            <template #default="scope">
                <div class="address">
                    {{ formatFullAddress(scope.row) }}
                </div>
            </template>
        </el-table-column>
        <el-table-column prop="isDefault" label="默认地址" width="100">
            <template #default="scope">
                <el-tag :type="scope.row.isDefault ? 'success' : 'info'">
                    {{ scope.row.isDefault ? '是' : '否' }}
                </el-tag>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
            <template #default="scope">
                <div class="operation-cell">
                    <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </div>
            </template>
        </el-table-column>
    </el-table>

    <div class="pagination-container">
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[2, 10, 20, 50]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalCount">
        </el-pagination>
    </div>

    <div v-if="!loading && addressData.length === 0" class="loading-text">
        暂无地址数据
    </div>

    <el-dialog :title="addressForm.addressId ? '编辑收货地址' : '添加收货地址'" :visible.sync="dialogVisible" width="50%">
        <el-form ref="addressFormRef" :model="addressForm" label-width="100px">
            <el-form-item label="收件人" prop="receiverName" :rules="[{ required: true, message: '请输入收件人姓名', trigger: 'blur' }]">
                <el-input v-model="addressForm.receiverName"></el-input>
            </el-form-item>
            <el-form-item label="联系电话" prop="phone" :rules="[{ required: true, message: '请输入联系电话', trigger: 'blur' }]">
                <el-input v-model="addressForm.phone"></el-input>
            </el-form-item>
            <el-form-item
                    label="所在地区"
                    prop="regionId"
                    :rules="[{
                    validator: validateRegion,
                    trigger: 'change',
                    required: true,
                    message: '请选择完整的省市区'
                }]">
                <div class="region-selector">
                    <el-select
                            v-model="provinceId"
                            placeholder="选择省"
                            @change="handleProvinceChange"
                            clearable>
                        <el-option
                                v-for="item in provinces"
                                :key="item.regionId"
                                :label="item.regionName"
                                :value="item.regionId">
                        </el-option>
                    </el-select>
                    <el-select
                            v-model="cityId"
                            placeholder="选择市"
                            @change="handleCityChange"
                            :disabled="!provinceId"
                            clearable>
                        <el-option
                                v-for="item in cities"
                                :key="item.regionId"
                                :label="item.regionName"
                                :value="item.regionId">
                        </el-option>
                    </el-select>
                    <el-select
                            v-model="districtId"
                            placeholder="选择区"
                            @change="handleDistrictChange"
                            :disabled="!cityId"
                            clearable>
                        <el-option
                                v-for="item in districts"
                                :key="item.regionId"
                                :label="item.regionName"
                                :value="item.regionId">
                        </el-option>
                    </el-select>
                </div>
            </el-form-item>
            <el-form-item label="详细地址" prop="detailAddress" :rules="[{ required: true, message: '请输入详细地址', trigger: 'blur' }]">
                <el-input v-model="addressForm.detailAddress"></el-input>
            </el-form-item>
            <el-form-item label="默认地址">
                <el-switch v-model="addressForm.isDefault"></el-switch>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAddress">确定</el-button>
        </template>
    </el-dialog>
</div>

<script src="../js/vue.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<script src="../js/element-ui/lib/index.js"></script>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                addressData: [],
                loading: true,
                multipleSelection: [],
                currentPage: 1,
                pageSize: 10,
                totalCount: 0,
                dialogVisible: false,

                // 地址表单
                addressForm: {
                    receiverName: '',
                    phone: '',
                    detailAddress: '',
                    isDefault: false,
                    regionId: null
                },

                // 三级联动数据
                provinceId: null,
                cityId: null,
                districtId: null,
                provinces: [],
                cities: [],
                districts: [],

                // 存储地区名称
                regionNames: {
                    province: '',
                    city: '',
                    district: ''
                },
                regionMap: {}, // 用于存储regionId到地区对象的映射
                // 添加地区验证状态
                regionValidated: false
            }
        },
        methods: {
            // 新增验证方法
            validateRegion(rule, value, callback) {
                // 如果已经选择了区级，则验证通过
                if (this.districtId) {
                    this.regionValidated = true;
                    callback();
                } else {
                    this.regionValidated = false;
                    callback(new Error('请选择完整的省市区'));
                }
            },
            // 修改地区选择处理方法
            handleProvinceChange(val) {
                this.cityId = null;
                this.districtId = null;
                this.districts = [];
                this.addressForm.regionId = null;

                if (val) {
                    this.loadCities(val).then(() => {
                        this.$refs.addressFormRef.validateField('regionId');
                    });
                } else {
                    this.$refs.addressFormRef.validateField('regionId');
                }
            },
            handleCityChange(val) {
                this.districtId = null;
                this.addressForm.regionId = null;

                if (val) {
                    this.loadDistricts(val).then(() => {
                        this.$refs.addressFormRef.validateField('regionId');
                    });
                } else {
                    this.$refs.addressFormRef.validateField('regionId');
                }
            },

            handleDistrictChange(val) {
                this.addressForm.regionId = val;
                this.$refs.addressFormRef.validateField('regionId');
            },
            formatFullAddress(row) {
                const { province, city, district, detailAddress } = row;
                let fullAddress = [];

                // 添加省（直辖市不重复显示）
                if (province && (!city || city !== province)) {
                    fullAddress.push(province);
                }

                // 添加市（跳过"市辖区"）
                if (city && city !== "市辖区") {
                    fullAddress.push(city);
                }

                // 添加区县
                if (district) {
                    fullAddress.push(district);
                }

                // 添加详细地址
                if (detailAddress) {
                    fullAddress.push(detailAddress);
                }

                return fullAddress.join("") || "无地址信息";
            },
            // 初始化加载省份
            loadProvinces() {
                axios.get('/user/getRegions', { params: { parentId: 0 } })
                    .then(response => {
                        if (response.data.code === 20041) {
                            this.provinces = response.data.data;
                        }
                    });
            },

            // 修改loadCities和loadDistricts方法返回Promise
            loadCities(provinceId) {
                this.cityId = null;
                this.districtId = null;
                this.districts = [];

                if (!provinceId) return Promise.resolve([]);

                return axios.get('/user/getRegions', { params: { parentId: provinceId } })
                    .then(response => {
                        if (response.data.code === 20041) {
                            this.cities = response.data.data;
                            return this.cities;
                        }
                        return [];
                    });
            },

            // 加载区县
            loadDistricts(cityId) {
                this.districtId = null;

                if (!cityId) return Promise.resolve([]);

                return axios.get('/user/getRegions', { params: { parentId: cityId } })
                    .then(response => {
                        if (response.data.code === 20041) {
                            this.districts = response.data.data;
                            return this.districts;
                        }
                        return [];
                    });
            },

            // 提交地址
            // 修改submitAddress方法，移除手动验证
            submitAddress() {
                this.$refs.addressFormRef.validate(valid => {
                    if (valid) {
                        const formData = {
                            addressId: this.addressForm.addressId,
                            receiverName: this.addressForm.receiverName,
                            phone: this.addressForm.phone,
                            detailAddress: this.addressForm.detailAddress,
                            isDefault: this.addressForm.isDefault ? 1 : 0,
                            regionId: this.districtId
                        };

                        const request = this.addressForm.addressId
                            ? axios.put('/user/updateAddress', formData)
                            : axios.post('/user/addAddress', formData);

                        request.then(response => {
                            const expectedCode = this.addressForm.addressId ? 20031 : 20011;
                            if (response.data.code === expectedCode) {
                                this.$message.success(this.addressForm.addressId ? '更新成功' : '添加成功');
                                this.resetForm();
                                this.dialogVisible = false;
                                this.fetchAddressData();
                            } else {
                                this.$message.error(response.data.msg || '操作失败');
                            }
                        }).catch(error => {
                            this.$message.error('操作失败: ' + (error.response?.data?.msg || error.message));
                        });
                    }
                });
            },

            // 修改后的resetForm方法
            resetForm() {
                this.addressForm = {
                    receiverName: '',
                    phone: '',
                    detailAddress: '',
                    isDefault: false,
                    regionId: null
                };
                this.provinceId = null;
                this.cityId = null;
                this.districtId = null;
                this.cities = [];
                this.districts = [];
                this.regionValidated = false;

                // 清除验证状态
                if (this.$refs.addressFormRef) {
                    this.$nextTick(() => {
                        this.$refs.addressFormRef.clearValidate();
                    });
                }
            },
            // 打开新增对话框
            handleAdd() {
                this.dialogVisible = true;
                this.resetForm();
                if (this.provinces.length === 0) {
                    this.loadProvinces();
                }
            },

            // 获取地址列表 - 保持与旧页面相同的逻辑
            fetchAddressData() {
                console.log('Fetching addresses, page:', this.currentPage, 'size:', this.pageSize);
                this.loading = true;
                axios.get('/user/getUserAddressList', {
                    params: {
                        pageNum: this.currentPage,
                        pageSize: this.pageSize
                    }
                }).then(response => {
                    console.log('API Response:', response.data);
                    if (response.data.code === 20041) {
                        this.addressData = response.data.data.list || [];
                        this.totalCount = response.data.data.total || 0;
                    } else {
                        this.$message.error(response.data.msg || '获取地址列表失败');
                    }
                }).catch(error => {
                    console.error('Request failed:', error);
                    this.$message.error('请求出错: ' + error.message);
                }).finally(() => {
                    this.loading = false;
                });
            },

            handleSelectionChange(val) {
                this.multipleSelection = val;
            },

            setDefaultAddress() {
                if (this.multipleSelection.length !== 1) return;
                const selected = this.multipleSelection[0];
                this.$confirm('确定设为默认地址吗？', '提示')
                    .then(() => {
                        axios.post('/user/setDefaultAddress', {
                            addressId: selected.addressId
                        }).then(() => {
                            this.$message.success('设置成功');
                            this.fetchAddressData();
                        });
                    });
            },

            handleSizeChange(val) {
                this.pageSize = val;
                this.fetchAddressData();
            },

            handleCurrentChange(val) {
                this.currentPage = val;
                this.fetchAddressData();
            },

            // 修改后的handleEdit方法
            handleEdit(row) {
                this.dialogVisible = true;
                this.addressForm = {
                    addressId: row.addressId,
                    receiverName: row.receiverName,
                    phone: row.phone,
                    detailAddress: row.detailAddress,
                    isDefault: row.isDefault === 1,
                    regionId: row.regionId
                };

                // 重置地区选择
                this.provinceId = null;
                this.cityId = null;
                this.districtId = null;
                this.cities = [];
                this.districts = [];
                this.regionValidated = false;

                // 如果有关联的区域ID，则加载地区链
                if (row.regionId) {
                    this.loadRegionChain(row.regionId).then(() => {
                        // 设置验证状态
                        this.regionValidated = true;
                        // 手动触发验证
                        this.$nextTick(() => {
                            this.$refs.addressFormRef.validateField('regionId');
                        });
                    });
                }
            },
            // 根据regionId加载完整的省市区链
            async loadRegionChain(regionId) {
                try {
                    // 1. 获取所有省份
                    const provincesRes = await axios.get('/user/getRegions', { params: { parentId: 0 } });
                    if (provincesRes.data.code !== 20041) {
                        throw new Error('获取省份数据失败');
                    }

                    // 2. 查找匹配的区县
                    let targetProvince = null;
                    let targetCity = null;
                    let targetDistrict = null;

                    for (const province of provincesRes.data.data) {
                        // 获取该省份下的城市
                        const citiesRes = await axios.get('/user/getRegions', {
                            params: { parentId: province.regionId }
                        });
                        if (citiesRes.data.code !== 20041) continue;

                        for (const city of citiesRes.data.data) {
                            // 获取该城市下的区县
                            const districtsRes = await axios.get('/user/getRegions', {
                                params: { parentId: city.regionId }
                            });
                            if (districtsRes.data.code !== 20041) continue;

                            // 查找目标区县
                            const district = districtsRes.data.data.find(d => d.regionId === regionId);
                            if (district) {
                                targetProvince = province;
                                targetCity = city;
                                targetDistrict = district;
                                break;
                            }
                        }
                        if (targetDistrict) break;
                    }

                    if (targetDistrict) {
                        // 设置选中的省市区
                        this.provinceId = targetProvince.regionId;
                        this.cities = await this.loadCities(this.provinceId);
                        this.cityId = targetCity.regionId;
                        this.districts = await this.loadDistricts(this.cityId);
                        this.districtId = targetDistrict.regionId;

                        // 更新表单中的regionId
                        this.addressForm.regionId = this.districtId;
                    } else {
                        this.$message.error('未找到对应的地区信息');
                    }
                } catch (error) {
                    console.error('加载地区链失败:', error);
                    this.$message.error('加载地区信息失败');
                }
            },


            handleDelete(row) {
                this.$confirm('确定删除该地址吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.delete(`/user/deleteAddress/${row.addressId}`)
                        .then(response => {
                            if (response.data.code === 20021) {
                                this.$message.success('删除成功');
                                this.fetchAddressData();
                            } else {
                                this.$message.error(response.data.msg || '删除失败');
                            }
                        })
                        .catch(error => {
                            this.$message.error('删除失败: ' + error.message);
                        });
                }).catch(() => {
                    this.$message.info('已取消删除');

                });
            }
        },
        mounted() {
            this.fetchAddressData();
            this.loadProvinces(); // 预加载省份数据
        }
    });
</script>
</body>
</html>